﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.WebApp.Models;
namespace XSTDZ.ERP.WebApp.Controllers
{
    [NoAuthorizated]
    public class HomeController : Controller
    {
        private readonly IPermisstionService permissionServiceImpl = ServiceLocator.Instance.GetService<IPermisstionService>();
        private readonly IUserService userServiceImpl = ServiceLocator.Instance.GetService<IUserService>();
        //
        // GET: /Home/
        //判断用户有的权限

        public ActionResult Index()
        {
            //new XSTDZ.ERP.WebApp.Models.DataInit();

            

            var operations = permissionServiceImpl.GetAllOperations();
            ViewBag.LoginName = "Admin";
            var userID = UserModel.GetLoginUserId(this.HttpContext);
            if (userID.ToString().ToUpper() != XSTDZ.ERP.Infrastructure.SystemConfig.AdminId.ToUpper())
            {
               
                ViewBag.LoginName = userServiceImpl.GetUser(userID).AccountName;

                var permissionIds = userServiceImpl.GetPermissionIds(userID);
               if (permissionIds != null && permissionIds.Count() != 0)
               {
                   if (operations != null && operations.Count() != 0)
                   {
                       var itemMenus = operations.Where(t => permissionIds.Contains(t.PermissionID ?? Guid.Empty));
                       var parentIds = itemMenus.Select(t => t.ParentId).ToList();
                       var barMenus = operations.Where(t => t.Id == t.ParentId).Where(t => parentIds.Contains(t.Id));
                       operations = barMenus.Concat(itemMenus);
                   }
               }
            }
            operations.Each(o =>o.PermissionDto= o.PermissionDto ?? new XSTDZ.ERP.Application.DataContracts.PermissionDto());
            operations = operations.OrderByDescending(t => t.OrderNum);
            return View(operations);
        }
         [NoAuthorizated("Welcome")]
        public ActionResult Welcome()
        {
            return View();
        }
        
    }
}
